﻿using System;
using System.Text;

namespace Bangle.SerialPort.Messages
{
    public class BufferReader : IBufferReader
    {
        private byte[] _data;
        private int _offset;

        public BufferReader(byte[] data)
        {
            _data = data;
            _offset = 0;
        }

        public byte[] GetData()
        {
            return _data;
        }


        public byte ReadByte()
        {
            return _data[_offset++];
        }

        public float ReadFloat()
        {
            var offset = _offset;
            _offset += 4;

            return BitConverter.ToSingle(new byte[]
            {
                _data[offset+3],
                _data[offset+2],
                _data[offset+1],
                _data[offset],
            }, 0);
        }

        public virtual UInt16 ReadUInt16()
        {
            var offset = _offset;
            _offset += 2;
            return BitConverter.ToUInt16(new byte[]
            {
                _data[offset+1],
                _data[offset],
            }, 0);
        }

        public virtual UInt32 ReadUInt32()
        {
            var offset = _offset;
            _offset += 4;
            return BitConverter.ToUInt32(new byte[]
            {
                _data[offset+3],
                _data[offset+2],
                _data[offset+1],
                _data[offset],
            }, 0);
        }

        public virtual long ReadLong32()
        {
            var offset = _offset;
            _offset += 4;
            long v = _data[offset];
            v = (v << 8) | _data[offset + 1];
            v = (v << 8) | _data[offset + 2];
            v = (v << 8) | _data[offset + 3];
            return v;
        }

        public virtual string ReadString(int len)
        {
            var offset = _offset;
            _offset += len;
            //排队0x0
            var l = 0;
            for (var i = 0; i < len; i++)
            {
                if (_data[offset + i] == 0x0)
                {
                    break;
                }
                l++;
            }
            return Encoding.ASCII.GetString(_data, offset, l);
        }

        public virtual double ReadDouble16(double d)
        {
            var v = ReadUInt16();
            return v / d;
        }

        public virtual double ReadDouble32(double d)
        {
            var v = ReadUInt32();
            return v / d;
        }

        public virtual DateTime ReadDateTime()
        {
            long time = Convert.ToInt64(ReadUInt32());
            return DateTimeOffset.FromUnixTimeSeconds(time).LocalDateTime;
        }
    }
}
